<template>
    <div class="choose_printer_container">
        <el-form ref="printerForm" :model="formData" :rules="rules" label-width="100px">
            <el-form-item label="选择打印机" prop="printer" v-if="activeSocket">
                <el-select v-model="formData.printer" style="width: 95%;">
                    <el-option v-for="(item, index) in printerList" :key="index"
                               :label="item.name" :value="item.name" />
                </el-select>
            </el-form-item>
            <el-form-item label-width="0px" v-else>
                <div class="tips">
                    <p class="tip_item">客户端未连接，请先启动客户端；若未安装客户端，请先下载客户端安装</p>
                    <el-link :underline="false" @click="downloadClient('32')">32位客户端</el-link>
                    <el-link :underline="false" @click="downloadClient('64')">64位客户端</el-link>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import print from "@common/utils/print";
import { autoConnect, disAutoConnect, hiprint } from "@common/plugins/hiprint";

export default {
    name: "ChoosePrinter",
    props: {
        template: {
            type: Object,
            default: null,
        },
        data: {
            type: [Object, Array],
            default: null,
        },
        printMethod: {
            type: Function,
            default: null,
        },
    },
    data() {
        return {
            rules: {
                printer: [
                    { required: true, message: "请选择打印机", trigger: "change" },
                ],
            },
            formData: {
                printer: '',
            },
            printerList: [],
            activeSocket: false,
        };
    },
    beforeDestroy() {
        disAutoConnect();
    },
    mounted() {
        this.init();
    },
    methods: {
        async init() {
            const _this = this;
            _this.formData = {
                printer: '',
            };
            _this.activeSocket = false;
            _this.connect().then(() => {
                console.log('连接客户端成功！');
                _this.initPrinterList();
            });
        },
        connect() {
            return new Promise((resolve => {
                if (window.hiwebSocket.opened) {
                    resolve();
                    return;
                }
                autoConnect(status => {
                    if (status) {
                        resolve();
                    }
                });
            }));
        },
        initPrinterList() {
            const _this = this;
            _this.$hiPrint.refreshPrinterList(list => {
                _this.activeSocket = true;
                _this.$emit('event', {
                    type: 'disabledConfirmBtn',
                    value: false,
                });
                _this.printerList = list
                if (_this.$utils.isNotEmptyList(list)) {
                    _this.printer = list[0].name;
                    _this.formData = {
                        printer: list[0].name,
                    };
                }
            });
        },
        downloadClient(type) {
            let link = document.createElement("a");
            link.href = `/static/client/hiprint_win_x${ type }-1.0.5.exe`;
            link.download = `hiprint_win_x${ type }-1.0.5.exe`;
            link.click();
            window.URL.revokeObjectURL(link.href);
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('printerForm');
            if (valid) {
                if (typeof _this.printMethod === 'function') {
                    valid = await _this.printMethod(_this.formData.printer);
                }
                if (_this.template && _this.data) {
                    valid = await _this.doPrint();
                    if (valid) {
                        return true;
                    }
                }
                return _this.formData.printer;
            }
            return undefined;
        },
        async doPrint() {
            const _this = this;
            if (!_this.activeSocket) {
                return false;
            }
            let printTemplate = new hiprint.PrintTemplate({
                template: _this.template,
            });
            print.showLoading('正在打印.....');
            await _this.handlePrintMethod(printTemplate, _this.data, '打印预览');
            print.hideLoading();
            return true;
        },
        handlePrintMethod(template, printData, title) {
            const _this = this;
            return new Promise(resolve => {
                template.print2(printData, {
                    printer: _this.formData.printer,
                    title,
                });
                template.on('printSuccess', data => {
                    console.log('打印完成', data);
                    _this.$message.success('打印完成');
                    resolve(true);
                });
                template.on('printError', data => {
                    console.log('打印失败', data);
                    _this.$message.error('打印失败');
                    resolve(false);
                });
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.choose_printer_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    /deep/ .tips {
        font-size: 14px;
        color: red;

        .tip_item {
            height: 24px;
            line-height: 24px;
        }

        a {
            text-decoration: none;
            vertical-align: baseline;

            &:hover {
                text-decoration: none;
            }
        }
    }
}
</style>
